<?php
/**
 * 根据品类id获取商品分类以及品类的小部件
 * Created by PhpStorm.
 * User: FDG296
 * Date: 2017/9/14
 * Time: 15:10
 */
namespace frontend\widget;

use common\models\CategoryRecommend;
use Yii;
use common\models\GoodsCategory;
use common\models\GoodsCateRelation;
use common\models\GoodsCategoryBrRelation;
use yii\base\Widget;

class TagMenuWidget extends Widget{

    public function run()
    {
        $data = Yii::$app->request->get();
        $category_list = array();
        $brand = array();
        $recommend_list = array();
        if(!empty($data['cate_id']) && is_numeric($data['cate_id'])){
            $cate_model = new GoodsCategory();
            $relation_model = new GoodsCateRelation();
            $brand_model = new GoodsCategoryBrRelation();
            $recommend_model = new CategoryRecommend();
            //获取一级分类id
            $tag_where = ['use_flg'=>1,'id'=>$data['cate_id']];
            $tag_list = $relation_model::find()->where($tag_where)->asArray()->one();
            if(!empty($tag_list)){
                $cate_where = ['id'=>$tag_list['category_id']];
                $cate_list = $cate_model::find()->where($cate_where)->asArray()->one();
                if(!empty($cate_list)){
                    //获取分类
                    $category_list = $cate_model->getCategoryListById($cate_list['parent_id']);
                    if(!empty($category_list)){
                        //获取品类
                        $cate_id = array_column($category_list,'id');
                        $relation_list = $relation_model->getRelationListByCateId($cate_id);
                        if(!empty($relation_list)){
                            foreach($category_list as &$value){
                                $value['tag_list'] = empty($relation_list[$value['id']]) ? '' : $relation_list[$value['id']];
                            }
                        }
                    }

                    //获取品牌
                    $brand_list = $brand_model->getCategoryBrandRelationListById($cate_list['parent_id']);
                    if(!empty($brand_list)){
                        foreach($brand_list as $val){
                            $brand[$val['group_id']]['group_name'] = $val['group_name'];
                            $brand[$val['group_id']]['brand_list'][] = $val;
                        }
                    }

                    //获取分类推荐
                    $recommend = $recommend_model->getRecommendList($cate_list['parent_id']);
                    if(!empty($recommend)){
                        $recommend_list = $recommend;
                    }
                }
            }
        }
        // 渲染视图
        return $this->render('@app/views/goods/category-menu', ['child_list'=>$category_list,'brand_list'=>$brand,'recommend_list'=>$recommend_list]);
    }
}